#include "stdafx.h"
#include "MouseCursor.h"

using namespace Ogre;

MouseCursor::MouseCursor(unsigned int width, unsigned int height): guiOverlay(0), cursorContainer(0)
{
	material = MaterialManager::getSingleton().load("Cursor", "General");
	cursorContainer = static_cast<Ogre::OverlayContainer*>(OverlayManager::getSingleton().createOverlayElement("Panel", "MouseCursor"));
	cursorContainer->setMaterialName("Cursor");
	cursorContainer->setPosition(0, 0);

	setWindowDimensions(width, height);

	guiOverlay = OverlayManager::getSingleton().create("MouseCursor");
	guiOverlay->setZOrder(650);
	guiOverlay->add2D(cursorContainer);
	guiOverlay->show();
	setVisible(true);
}

void MouseCursor::setWindowDimensions( unsigned int width, unsigned int height )
{
	windowWidth = (width > 0) ? static_cast<Real>(width) : 1;
	windowHeight = (height > 0) ? static_cast<Real>(height) : 1;

	std::pair<size_t, size_t> dim = material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getTextureDimensions();

	cursorContainer->setWidth(dim.first / windowWidth);
	cursorContainer->setHeight(dim.second / windowHeight);
}

void MouseCursor::setVisible( bool visible )
{
	if(visible) {
		cursorContainer->show();
	} else {
		cursorContainer->hide();
	}
}

void MouseCursor::updatePosition( int x, int y )
{
	Real rx = static_cast<Real>(x) / windowWidth;
	Real ry = static_cast<Real>(y) / windowHeight;
	cursorContainer->setPosition(clamp(rx, 0.0f, 1.0f), clamp(ry, 0.0f, 1.0f));
}

Ogre::Real MouseCursor::clamp( Ogre::Real a, Ogre::Real min, Ogre::Real max )
{
	if (a < min) {
		return min;
	}
	if (a > max) {
		return max;
	} 
	return a;
}

